var async = require('async');
var helpers = require('../../../helpers/aws');

module.exports = {
    title: 'RDS MySQL Vulnerability Check',
    category: 'RDS',
    severity: 'Medium',
    description: ' Ensures RDS MySQL instances are not vulnerable to specific CVEs.',
    more_info: 'Vulnerabilities in RDS MySQL instances can pose significant risks to the security and integrity of your database environment. By identifying and addressing these vulnerabilities, you can protect your data from unauthorized access, data tampering, or privilege escalation.',
    link: 'https://aws.amazon.com/security/security-bulletins/mysql-5-5-and-5-6-security-advisory/',
    recommended_action: 'Update the MySQL engine version to a more recent, patched version to mitigate the vulnerabilities.',
    apis: ['RDS:describeDBInstances'],
    realtime_triggers: ['rds:CreateDBInstance', 'rds:ModifyDBInstance', 'rds:RestoreDBInstanceFromDBSnapshot', 'rds:RestoreDBInstanceFromS3','rds:DeleteDBInstance'], 

    run: function(cache, settings, callback) {
        var results = [];
        var source = {};
        var regions = helpers.regions(settings);

        async.each(regions.rds, function(region, rcb) {
            var describeDBInstances = helpers.addSource(cache, source,
                ['rds', 'describeDBInstances', region]);

            if (!describeDBInstances) return rcb();

            if (describeDBInstances.err || !describeDBInstances.data) {
                helpers.addResult(results, 3,
                    `Unable to query for RDS instances: ${helpers.addError(describeDBInstances)}`, region);
                return rcb();
            }

            if (!describeDBInstances.data.length) {
                helpers.addResult(results, 0, 'No RDS instances found', region);
                return rcb();
            }

            describeDBInstances.data.forEach(instance => {
                if (!instance.DBInstanceArn || !instance.Engine) return;

                if (instance.Engine && instance.Engine.toLowerCase().includes('mysql')) {
                    const isVulnerable = instance.EngineVersion.match(/^(5\.5\.(?:[0-3][0-9]|[0-9])|5\.6\.(?:[0-1][0-9]|[0-9]|20))$/);

                    if (isVulnerable) {
                        helpers.addResult(results, 2, 'RDS MySQL instance is vulnerable', region, instance.DBInstanceArn);
                    } else {
                        helpers.addResult(results, 0, 'No vulnerabilities found in RDS MySQL instance', region, instance.DBInstanceArn);
                    }    
                } else {
                    helpers.addResult(results, 0, 'RDS does not have MYSQL instance', region);
                }
            });

            rcb();
        }, function() {
            callback(null, results, source);
        });
    }
};
